package cn.edu.baiyunu.myapplication.ui.specs

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import cn.edu.baiyunu.myapplication.data.model.PhotoSpec
import cn.edu.baiyunu.myapplication.data.model.PhotoSpecProvider
import cn.edu.baiyunu.myapplication.data.repository.PreferenceRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 规格类别枚举
 */
enum class SpecCategory(val title: String) {
    ALL("全部"),
    DOMESTIC("国内证件"),
    INTERNATIONAL("国际签证"),
    RESUME("求职简历"),
    STUDENT("学生证件"),
    SOCIAL("社交媒体")
}

/**
 * 规格页面ViewModel - 管理规格数据和UI状态
 */
class SpecsViewModel(
    private val preferenceRepository: PreferenceRepository
) : ViewModel() {
    
    // 所有规格列表
    private val _allSpecs = MutableLiveData<List<PhotoSpec>>()
    val allSpecs: LiveData<List<PhotoSpec>> = _allSpecs
    
    // 热门规格列表
    private val _popularSpecs = MutableLiveData<List<PhotoSpec>>()
    val popularSpecs: LiveData<List<PhotoSpec>> = _popularSpecs
    
    // 当前选中的分类
    private val _selectedCategory = MutableStateFlow(SpecCategory.ALL)
    val selectedCategory: StateFlow<SpecCategory> = _selectedCategory.asStateFlow()
    
    // 搜索关键词
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()
    
    // 当前筛选后的规格列表
    private val _filteredSpecs = MutableLiveData<List<PhotoSpec>>()
    val filteredSpecs: LiveData<List<PhotoSpec>> = _filteredSpecs
    
    // 分类规格映射
    private val categorySpecsMap = mutableMapOf<SpecCategory, List<PhotoSpec>>()
    
    init {
        loadSpecsData()
    }
    
    /**
     * 加载规格数据
     */
    private fun loadSpecsData() {
        val allSpecsList = PhotoSpecProvider.getAllSpecs()
        _allSpecs.value = allSpecsList
        _popularSpecs.value = PhotoSpecProvider.getPopularSpecs()
        
        // 初始化分类数据
        initCategoryData(allSpecsList)
        
        // 初始时显示所有规格
        _filteredSpecs.value = allSpecsList
    }
    
    /**
     * 初始化分类数据
     */
    private fun initCategoryData(allSpecs: List<PhotoSpec>) {
        // 这里是简化的分类逻辑，实际项目中可能需要从API获取或基于规格属性进行分类
        val domesticSpecs = allSpecs.filter { 
            it.name.contains("寸") || it.name.contains("身份证") || it.name.contains("驾驶证")
        }
        val internationalSpecs = allSpecs.filter { 
            it.name.contains("护照") || it.name.contains("签证") 
        }
        val resumeSpecs = allSpecs.filter { 
            it.name.contains("简历") || it.name.contains("求职") || it.name.contains("工作证") 
        }
        val studentSpecs = allSpecs.filter { 
            it.name.contains("学生") || it.name.contains("学校") || it.name.contains("学历") 
        }
        val socialSpecs = allSpecs.filter { 
            it.name.contains("社交") || it.name.contains("证件照") 
        }
        
        categorySpecsMap[SpecCategory.ALL] = allSpecs
        categorySpecsMap[SpecCategory.DOMESTIC] = domesticSpecs
        categorySpecsMap[SpecCategory.INTERNATIONAL] = internationalSpecs
        categorySpecsMap[SpecCategory.RESUME] = resumeSpecs
        categorySpecsMap[SpecCategory.STUDENT] = studentSpecs
        categorySpecsMap[SpecCategory.SOCIAL] = socialSpecs
    }
    
    /**
     * 设置当前选中的分类
     */
    fun setCategory(category: SpecCategory) {
        _selectedCategory.value = category
        updateFilteredSpecs()
    }
    
    /**
     * 设置搜索关键词
     */
    fun setSearchQuery(query: String) {
        _searchQuery.value = query
        updateFilteredSpecs()
    }
    
    /**
     * 根据当前分类和搜索词更新过滤后的规格列表
     */
    private fun updateFilteredSpecs() {
        val category = _selectedCategory.value
        val query = _searchQuery.value.trim().lowercase()
        
        // 先按分类过滤
        val specsByCategory = categorySpecsMap[category] ?: _allSpecs.value ?: emptyList()
        
        // 再按搜索词过滤
        val filteredBySearch = if (query.isEmpty()) {
            specsByCategory
        } else {
            specsByCategory.filter { 
                it.name.lowercase().contains(query) || 
                it.description.lowercase().contains(query)
            }
        }
        
        _filteredSpecs.value = filteredBySearch
    }
    
    /**
     * 获取规格详情
     */
    fun getSpecDetail(specId: String): PhotoSpec? {
        return _allSpecs.value?.find { it.id == specId }
    }
}

/**
 * SpecsViewModel工厂类
 */
class SpecsViewModelFactory(
    private val preferenceRepository: PreferenceRepository
) : ViewModelProvider.Factory {
    
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(SpecsViewModel::class.java)) {
            return SpecsViewModel(preferenceRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
} 